package com.hsource.doctorcenter.util;

import org.apache.commons.codec.binary.Hex;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class SignParams {



    private Map<String, String> params = new HashMap<>();

    public Map<String, String> getParams() {
        return params;
    }

    public SignParams paramEntry(String key, String value){
        if(this instanceof SignParams){
            ((SignParams) this).putParam(key, value);
        }
        return this;
    }

    static public boolean callBackSign(Map<String,Object> callBackDataMap)throws ParseException, NoSuchAlgorithmException {
        String service_problem_id="";
        if(callBackDataMap.containsKey("service_id")){
            service_problem_id=callBackDataMap.get("service_id").toString();
        }
        if(callBackDataMap.containsKey("problem_id")){
            service_problem_id=callBackDataMap.get("problem_id").toString();
        }
        //qHZNltCEsGJRBzof 正式环境
        //yu6Zb9HUhRInXgsK 测试环境
       return  getSign(StaticValue.PARTNER_KEY,callBackDataMap.get("atime").toString(),service_problem_id).equals(callBackDataMap.get("sign").toString());
    }

    static public SignParams newBuilder(String userId) throws ParseException, NoSuchAlgorithmException {
        String atime = atime();
        return new SignParams()
                .paramEntry("user_id",userId)
                .paramEntry("partner","bjgrg")
                .paramEntry("atime",atime)
                .paramEntry("sign",getSign(StaticValue.PARTNER_KEY, atime, userId));
    }

    public void setParams(Map<String, String> params) {
        this.params = params;
    }

    public void putParam(String key, String value) {
        params.put(key, value);
    }

    public Object removeParam(String key) {
        return params.remove(key);
    }


    public static String atime() throws ParseException {
        Calendar cal=Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        Date date = sdf.parse("1970-01-01 00:00:00");
        cal.setTime(date);
        Calendar cal1=Calendar.getInstance();
        return String.valueOf((cal1.getTime().getTime()-cal.getTime().getTime())/1000);
    }

    // 计算 Sign
    public static String getSign(String partner_key, String atime, String user_id)
            throws NoSuchAlgorithmException {
        String info = partner_key + atime + user_id;
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        byte[] srcBytes = info.getBytes();
        md5.update(srcBytes);
        byte[] resultBytes = md5.digest();
        String resultString = new String(new Hex().encode(resultBytes));
        return resultString.substring(8, 24);
    }
}
